package com.dbq.fast.business.login.business;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import com.dbq.fast.App;
import com.dbq.fast.R;
import com.dbq.fast.analysis.EventConstant;
import com.dbq.fast.analysis.YibaAnalysis;
import com.dbq.fast.business.login.bean.CustomProfile;
import com.dbq.fast.business.login.bean.FbProfile;
import com.dbq.fast.common.json.GsonT;
import com.dbq.fast.util.ProgressDialogUtil;
import com.dbq.fast.util.SystemUtil;
import com.facebook.AccessToken;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.GraphRequest;
import com.facebook.GraphResponse;
import com.facebook.login.LoginManager;
import com.facebook.login.LoginResult;

import org.json.JSONObject;

import java.util.Arrays;
import java.util.List;



/**
 * <p>
 * FB自定义登录按钮登录方式
 */

public class FbLoginBiz {

    CallbackManager callbackManager;
    FbLoginListener fbLoginListener;
    List<String> permissions;
    Activity activity;

    public FbLoginBiz(Activity activity) {
        this.activity = activity;
        permissions = Arrays.asList("email", "user_likes", "user_status", "user_photos", "user_birthday", "public_profile", "user_friends");

        callbackManager = CallbackManager.Factory.create();
        LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
            @Override
            public void onSuccess(LoginResult loginResult) {
                if (fbLoginListener != null) {
                    fbLoginListener.fbLoginSuccess(loginResult.getAccessToken());
                }
            }

            @Override
            public void onCancel() {
                YibaAnalysis.getInstance().event(App.getContext(), EventConstant.EVENT_FB_LOGIN_CANCEL);
                ProgressDialogUtil.hideProgress();
                Log.e("vpn_log", "fblogin:onCancel");
//                Toast.makeText(App.getContext(), App.getContext().getString(R.string.tip_login_cancel), Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onError(FacebookException error) {
                YibaAnalysis.getInstance().event(App.getContext(), EventConstant.EVENT_FB_LOGIN_EXCEP);
                ProgressDialogUtil.hideProgress();
                Toast.makeText(App.getContext(), App.getContext().getString(R.string.tip_retry_network_error), Toast.LENGTH_SHORT).show();
                Log.e("vpn_log", "fblogin:error:" + error.toString());
            }
        });
    }

    public void login() {
        LoginManager.getInstance().logInWithReadPermissions(activity, permissions);
    }

    public void logOut() {
        LoginManager.getInstance().logOut();
    }

    public void destory(){
        LoginManager.getInstance().unregisterCallback(callbackManager);
    }

    public void getProfile(AccessToken accessToken) {
        GraphRequest request = GraphRequest.newMeRequest(accessToken, new GraphRequest.GraphJSONObjectCallback() {
            @Override
            public void onCompleted(JSONObject object, GraphResponse response) {
                if (object != null) {
                    FbProfile selfInfo = GsonT.parseJson(object.toString(), FbProfile.class);
                    if (fbLoginListener != null) {
                        fbLoginListener.fbAccessProfile(selfInfo);
                    }
                }else {
                    YibaAnalysis.getInstance().event(App.getContext(), EventConstant.EVENT_FB_LOGIN_GET_INFO);
                }
            }
        });

        Bundle parameters = new Bundle();
        parameters.putString("fields", "id,name,link,gender,birthday,email,picture,locale,updated_time,timezone,age_range,first_name,last_name");
        request.setParameters(parameters);
        request.executeAsync();

    }

    public CustomProfile transProfile(FbProfile fbProfile) {
        CustomProfile profile = new CustomProfile();
        profile.setLoginChannel(2);
        profile.setPlatformId(fbProfile.getId());
        profile.setUsername(fbProfile.getName());
        if ("male".equals(fbProfile.getGender())) {
            profile.setGender(1);
            profile.setSex("1");
        } else if ("female".equals(fbProfile.getGender())) {
            profile.setGender(2);
            profile.setSex("2");
        }else {
            profile.setSex("3");
        }
        profile.setCountry(SystemUtil.getCountry(App.getContext()));
        profile.setEmail(fbProfile.getEmail());
        profile.setLink(fbProfile.getLink());
        profile.setTimezone(fbProfile.getTimezone());
        profile.setMinAge(fbProfile.getAge_range().getMin());
        profile.setMaxAge(fbProfile.getAge_range().getMax());
        if(fbProfile.getPicture() != null && fbProfile.getPicture().getData() != null){
            profile.setPicture(fbProfile.getPicture().getData().getUrl());
        }
        profile.setUuid(SystemUtil.getAndroidId(App.getContext()));
        if(fbProfile.getPicture() != null && fbProfile.getPicture().getData() != null) {
            profile.setIcon(fbProfile.getPicture().getData().getUrl());
        }

        return profile;
    }

    public void setLoginListener(FbLoginListener fbLoginListener) {
        this.fbLoginListener = fbLoginListener;
    }

    public CallbackManager getCallbackManager() {
        if (callbackManager == null) {
            callbackManager = CallbackManager.Factory.create();
        }
        return callbackManager;
    }

    public interface FbLoginListener {
        void fbLoginSuccess(AccessToken accessToken);

        void fbAccessProfile(FbProfile fbProfile);
    }

}
